package com.hycc.base;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class JUC {
    public static void main(String[] args) {
        //并发 多线程操作同一个资源类，把资源类丢入线程
        Ticket ticket = new Ticket();

        new Thread(()->{for (int i = 0; i < 40; i++)ticket.sale();},"a").start();
        new Thread(()->{for (int i = 0; i < 40; i++)ticket.sale();},"b").start();
        new Thread(()->{for (int i = 0; i < 40; i++)ticket.sale();},"c").start();

    }
}
//Lock接口锁的使用方法
//1 创建ReentrantLock
//2 加锁
//3 解锁
class Ticket{
    //属性、方法
    Lock lock= new ReentrantLock();
    private int number = 30;

    public void sale(){
        lock.lock();
        try {
            if(number>0){
                System.out.println(Thread.currentThread().getName()+"卖出了"+(number--)+"票，剩余："+number);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}